package org.sws.domain.strategy.service.rule.tree.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.sws.domain.strategy.enums.RuleLogicCheckTypeVO;
import org.sws.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import org.sws.domain.strategy.service.armory.IStrategyDispatch;
import org.sws.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.sws.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author sws
 * @Date 2025/2/25 11:34
 * @description: 奖品库存 - 扣减规则树节点
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date activityEndTime) {
        log.info("规则过滤-奖品库存 userId:{} strategyId:{} awardId:{} ruleValue:{}", userId, strategyId, awardId, ruleValue);
        // redis 扣减库存
        Boolean subStockResult = strategyDispatch.subtractionAwardStock(strategyId, awardId, activityEndTime);
        if (subStockResult) {
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
            strategyDispatch.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .awardId(awardId)
                    .strategyId(strategyId)
                    .build());
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardData(DefaultTreeFactory.StrategyAwardData.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }
        // 如果库存不足，则直接返回放行
        log.warn("规则过滤-库存扣减-告警，库存不足。userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
